package com.zjff.mobiletwo.service;

import com.taobao.api.internal.util.StringUtils;
import com.zjff.mobiletwo.dao.UserDao;
import com.zjff.mobiletwo.entity.ResultEntity;
import com.zjff.mobiletwo.entity.UserEntity;
import com.zjff.mobiletwo.service.util.Message;
import com.zjff.mobiletwo.service.util.RedisUtils;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    @Resource
    UserDao userDao;
    @Autowired
    RedisUtils redisUtils;
    private static final Logger logger = LoggerFactory.getLogger(UserService.class);

    /**
     * 通过用户手机号查找用户详情
     * @param phone 手机号
     * @return
     */
    public String getUserByPhone(String phone){
        UserEntity user = userDao.getUserByPhone(phone);
        if(user !=null){
            return ResultEntity.Success(null,userDao.getUserByPhone(phone),0,"获取成功!");
        }else {
            return ResultEntity.Fail(-10007,"该手机号未绑定用户!");
        }
    }

    /**
     * 根据用户id修改账号
     * @param id 用户id
     * @param username 原账号
     * @param newname 新账号
     * @param conname 确认账号
     * @return
     */
    public String updateUsername(int id,String username,String newname,String conname){
        UserEntity user = userDao.getUserDetailById(id);
        try{
            if (!user.getUsername().equals(username)){
                return ResultEntity.Fail(-10007,"原账号错误!");
            } else if (user.getUsername().equals(newname)) {
                return ResultEntity.Fail(-10007,"新账号不能与旧账号相同!");
            } else if (!newname.equals(conname)) {
                return ResultEntity.Fail(-10007,"两次账号输入不同!");
            }else {
                return ResultEntity.Success(null,userDao.updateUsername(conname,id),0,"修改账号成功!");
            }
        }catch(Exception e){
            logger.error(e.getMessage());
            e.printStackTrace();
            return ResultEntity.Fail(-10007,"修改账号失败!");
        }
    }
    /**
     * **修改邮箱
     * @param id 用户id
     * @param email 邮箱
     * @return JSON（String)
     */
    public String updateEmail(String email,int id){
        try{
            return ResultEntity.Success(null,userDao.updateEmail(email, id),0,"修改邮箱成功!");
        }catch(Exception e){
            logger.error(e.getMessage());
            e.printStackTrace();
            return ResultEntity.Fail(-10007,"修改邮箱失败!");
        }
    }
    /**
     * **修改昵称
     * @param id 用户id
     * @param pname 昵称
     * @return JSON（String)
     */
    public String updatePname(String pname,int id){
        try{
            return ResultEntity.Success(null,userDao.updatePname(pname, id),0,"修改昵称成功!");
        }catch(Exception e){
            logger.error(e.getMessage());
            e.printStackTrace();
            return ResultEntity.Fail(-10007,"修改昵称失败!");
        }
    }
    /**
     * **修改手机号
     * @param id 用户id
     * @param phone 手机号
     * @return JSON（String)
     */
    public String updatePhone(String phone,int id){
        try{
            return ResultEntity.Success(null,userDao.updatePhone(phone, id),0,"修改手机号成功!");

        }catch(Exception e){
            logger.error(e.getMessage());
            e.printStackTrace();
            return ResultEntity.Fail(-10007,"修改手机号失败!");
        }
    }

    /**
     * 添加密码用于手机短信注册无登录密码的情况
     * @param password 密码
     * @param id 用户id
     * @return
     */
    public String addPassword(String password,int id){
        UserEntity user = userDao.getUserDetailById(id);
        try{
            if(user.getPassword() == null){
                return ResultEntity.Success(null,userDao.addPassword(password, id),0,"添加密码成功!");
            }else {
                return ResultEntity.Fail(-10007,"该用户已有密码无需添加!");
            }
        }catch(Exception e){
            logger.error(e.getMessage());
            e.printStackTrace();
            return ResultEntity.Fail(-10007,"添加密码失败!");
        }
    }
    /**
     * 添加账号用于手机短信注册无账号的情况
     * @param username 账号(用户名)
     * @param id 用户id
     * @return
     */
    public String addUsername(String username,int id){
        UserEntity user = userDao.getUserDetailById(id);
        UserEntity userr =userDao.getUserByUsername(username);
        try{
            if (userr != null){
                return ResultEntity.Fail(-10007,"用户名被注册!");
            }else if (user.getUsername() == null){
                return ResultEntity.Success(null,userDao.addUsername(username, id),0,"添加账户成功!");
            }else {
                return ResultEntity.Fail(-10007,"该用户已有账号无需添加!");
            }
        }catch(Exception e){
            logger.error(e.getMessage());
            e.printStackTrace();
            return ResultEntity.Fail(-10007,"添加账户失败!");
        }
    }

    /**
     * **根据username删除用户详情
     * @param username 用户名
     * @return JSON（String)
     */
    public String deluser(String username){
        try{
            return ResultEntity.Success(null,userDao.deluser(username),0,"删除用户成功!");
        }catch(Exception e){
            logger.error(e.getMessage());
            e.printStackTrace();
            return ResultEntity.Fail(-10007,"删除用户失败!");
        }
    }
    /**
     * 通过用户手机号获取验证码
     * @param phone 手机号
     * @return
     */
    public String authcode_get(String phone) {
        UserEntity user = userDao.getUserByPhone(phone);
        if (user != null){
            if (StringUtils.isEmpty(phone)){
                return ResultEntity.Fail(-10007,"输入不能为空!");
            }else if (user ==null){
                return ResultEntity.Fail(-10007,"手机号未注册!");
            } else {
                String authcode = "1"+ RandomStringUtils.randomNumeric(5);//生成随机数,我发现生成5位随机数时，如果开头为0，发送的短信只有4位，这里开头加个1，保证短信的正确性
                redisUtils.set(phone,authcode);//将验证码存入缓存
                Message.messagePost(phone,authcode);//发送短息
                return "验证码为:" + authcode;
            }
        }else{
            System.out.println("用户不能为空");
            return ResultEntity.Fail(-10007,"用户不能为空!");
        }
    }

    /**
     * 验证码校验
     * @param phone    手机号
     * @param authcode 验证码
     * @return
     */
    public Object authcode(String phone, String authcode) {
        if (StringUtils.isEmpty(phone)){
            return ResultEntity.Fail(-10007,"输入不能为空!");
        }else if (!redisUtils.get(phone).equals(authcode)){
            return ResultEntity.Fail(-10007,"验证码错误!");
        }else {
            return ResultEntity.Success(null,phone,0,"校验成功!");
        }
    }

    /**
     * 验证码登录
     * @param phone    手机号
     * @param authcode 验证码
     * @return
     */
    public Object authcode_login(String phone, String authcode) {
        UserEntity user = userDao.getUserByPhone(phone);
        if (user != null){
           if (StringUtils.isEmpty(phone)){
               return ResultEntity.Fail(-10007,"输入不能为空!");
           }else if (user == null){
               return ResultEntity.Fail(-10007,"手机号未注册!");
           }else if (!redisUtils.get(phone).equals(authcode)){
               return ResultEntity.Fail(-10007,"验证码错误!");
           }else {
               return user;
           }
        }else{
            System.out.println("用户不能为空");
            return ResultEntity.Fail(-10007,"用户不能为空!");
        }
    }

    /**
     * 注册用户详情
     * @param username 用户名
     * @param password 密码
     * @param email 邮箱
     * @param phone 手机号
     * @param pname 昵称
     * @param gender 性别
     * @return
     */
    public String addUser(String username,String password,String email,String phone,String pname,int gender){
        try{
            UserEntity user = userDao.getUserByUsername(username);
            UserEntity userr = userDao.getUserByPhone(phone);
            if (user !=null){
                return ResultEntity.Fail(-10007,"用户名重复!");
            } else if (userr !=null) {
                return ResultEntity.Fail(-10007,"手机号重复!");
            }else {
                return ResultEntity.Success(null,userDao.addUser(username,password,email,phone,pname,gender));
            }
        }catch(Exception e){
            logger.error(e.getMessage());
            e.printStackTrace();
            return ResultEntity.Fail(-10007,"注册用户失败!");
        }
    }
    /**
     * 通过手机号获取验证码
     * @param phone 手机号
     * @return
     */
    public String authcode(String phone) {
        try{
            String authcode = "1"+ RandomStringUtils.randomNumeric(5);//生成随机数,我发现生成5位随机数时，如果开头为0，发送的短信只有4位，这里开头加个1，保证短信的正确性
            redisUtils.set(phone,authcode);//将验证码存入缓存
            Message.messagePost(phone,authcode);//发送短息
            return ResultEntity.Success(null,(authcode),0,"获取验证码成功!");
        }catch(Exception e){
            logger.error(e.getMessage());
            e.printStackTrace();
            return ResultEntity.Fail(-10007,"删除用户失败!");
        }
    }
    /**
     * 验证码注册
     * @param phone    手机号
     * @param authcode 验证码
     * @return
     */
    public String addUserByPhone(String phone,String authcode){
        UserEntity user = userDao.getUserByPhone(phone);
        try{
            if (user !=null){
                return ResultEntity.Fail(-10007,"该手机号已注册!");
            } else if (!redisUtils.get(phone).equals(authcode)){
                return ResultEntity.Fail(-10007,"验证码错误!");
            }else {
                return ResultEntity.Success(null,userDao.addUserByPhone(phone),0,"注册成功!");
            }
        }catch(Exception e){
            logger.error(e.getMessage());
            e.printStackTrace();
            return ResultEntity.Fail(-10007,"注册失败!");
        }
    }
    /**
     * @return JSON
     */
    public String getUserDetailById(int id) {
        try {
            return ResultEntity.Success(null,userDao.getUserDetailById(id),0,"获取成功!");
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            return ResultEntity.Fail(-10007,"上传失败!");
        }
    }

    public UserEntity Sel(int id) {
        return userDao.Sel(id);
    }

    public UserEntity login(String username, String password) {
        return userDao.login(username, password);
    }

    public String register(UserEntity user) {
        return userDao.register(user);
    }
    /**
     * 更改头像
     * @param avatar 头像URL（七牛云）
     * @param id 用户id
     * @return JSON
     */
    public int upLoadHeadImg(String avatar,int id) {
        return userDao.upHeadImg(avatar, id);
    }
}
